package com.hqyj.springCloudWeb.config;

import com.hqyj.entity.account.Resource;
import com.hqyj.entity.account.Role;
import com.hqyj.entity.account.User;
import com.hqyj.springCloudWeb.service.AccountOpenFeignClient;
import com.hqyj.springCloudWeb.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author yun
 * @date 2021-5-6 22:55
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private AccountOpenFeignClient accountOpenFeignClient;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //资源授权器
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User)principals.getPrimaryPrincipal();
        //获取该用户的角色列表
        List<Role> roles_db = accountOpenFeignClient.getRolesByUserId(user.getId());
        roles_db.stream().forEach(role -> {
            //将用户所拥有的每个角色加入资源授权器中
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //查询每个角色所拥有的资源
            List<Resource> resources_db = accountOpenFeignClient.getResourcesByRoleId(role.getId());
            resources_db.stream().forEach(resource -> {
                //将角色能访问的所有资源添加到资源授权器中
                simpleAuthorizationInfo.addStringPermission(resource.getPermission());
            });
        });
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String)token.getPrincipal();
        User user = accountOpenFeignClient.selectUserByUserName(userName);
        if(user == null){
            throw new UnknownAccountException("该用户不存在！");
        }
        /**
         * principal: 当前用户信息，可以是 user对象，也可以是用户名
         * credentials: 用户密码
         * realmName: 当前 realm 对象的唯一名字
         */
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
